package com.liu.concurrent.juc.locks;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 独占锁：写锁,只能一个线程去写
 * 共享锁：读锁,多个线程可同时读
 * @author liubo
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp, temp);
            }).start();
        }

        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp);
            }).start();
        }
    }

}

class MyCache {
    private volatile Map<Integer, Object> map = new HashMap<>();

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 写,只能一个线程去写
     *
     * @param key
     * @param value
     */
    public void put(Integer key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完毕" + key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * 读,多个线程可同时读
     *
     * @param key
     */
    public Object get(Integer key) {
        Object o = null;
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取" + key);
            o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完毕" + key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return o;
    }
}
